import { View } from 'wptd';
import cx from 'classnames';
import { useEffect, useRef, useState } from 'react';
import analyze from './analyze';

import S from './index.m.less';

/**
 * 实现思路
 * 如果overflow: hidden生效的话，元素的scrollHeight > clientHeight
 * 然后采取二分法查找临界点，start不溢出 end = start + 1 溢出
 * tip:
 * 找到临界点之后，把expandBtn插到最后一行，使用float:right的特性，保证其靠右
 * 直接塞到最后位置，有可能会导致expandBtn被挤掉，显示不出来
 * todo:
 * 如果字符串中包含emoji，可能会导致最后一个emoji无法正常显示
 */

const RIGHT_IDENT = 6;

export default function TextLine(props) {
    const {
        content = '',
        className,
        style,
        onClick,
        line,
        autoExpand = true,
        expandBtn = '展开',
        expandColor = '',
        onStateChange,
        ...otherProps
    } = props;

    const [state, setState] = useState({ isOverflow: false, start: -1 });
    const [expand, setExpand] = useState(false);
    const textRef = useRef();

    useEffect(() => {
        if (typeof content === 'string' && textRef.current) {
            const analyzeResult = analyze(textRef.current, content);
            setState(analyzeResult);
            // 通知更改结果
            onStateChange && onStateChange(analyzeResult);
        }
    }, [content, line, expand, onStateChange]);

    const handleClick = event => {
        autoExpand && setExpand(!expand);
        onClick && onClick(event, expand);
    };

    const notExpand = !expand && line > 0;
    const child = state.isOverflow && !expand && expandBtn ? (
        <>
            {content.slice(0, state.start - RIGHT_IDENT)}
            {!!expandBtn && (
                <span className={S.wptTextExpand} style={{ color: expandColor }}>
                    {expandBtn}
                </span>
            )}
            {content.slice(state.start - RIGHT_IDENT)}
        </>
    ) : (
        content
    );

    return (
        <View
            Tag="span"
            {...otherProps}
            className={cx(className, notExpand && S.wptTextLine, line && S.wptTextBlock)}
            style={{
                ...style,
                ...(notExpand && { WebkitLineClamp: line }),
            }}
            onClick={handleClick}
            domRef={textRef}
        >
            {child}
        </View>
    );
}
